#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "sthread.h"
#include "SimpleStats.h"
#include "OBLBasic_Table.h"


static const int verbose = 0;

struct args{
  OBLBasicTable *t;
  SimpleStats *s;
  int myId;
};

static void *doPhil(void *t);

int
main(int argc, char **argv)
{
  int ii;

  int nPhil = 10;
  sthread_t *phils;
  struct args *targs;
  OBLBasicTable table;
  SimpleStats s;

  if(argc > 1){
    int seed = atoi(argv[1]);
    printf("seeding with %d\n", seed);
    sutil_srandom(seed);
  }
  
  OBLT_init(&table, nPhil);
  SS_init(&s, nPhil, verbose, 1);

  phils = (sthread_t *)malloc(nPhil * sizeof(sthread_t));
  assert(phils);
  targs = (struct args *)malloc(nPhil * sizeof(struct args));
  assert(targs);
  for(ii = 0; ii < nPhil; ii++){
    targs[ii].t = &table;
    targs[ii].s = &s;
    targs[ii].myId = ii;
    sthread_create(&(phils[ii]), (void * (*)(void *))doPhil, (void *)(&(targs[ii])));
  }

  for(ii = 0; ii < 10; ii++){
    sthread_sleep(1, 0);
    SS_progress(&s);
    SS_printStats(&s);
  }

  exit(0);

}


static void *
doPhil(void *p)
{
  struct args *a = (struct args *)p;
  OBLBasicTable *t = a->t;
  SimpleStats *s = a->s;
  int myId = a->myId;

  printf("Thread %d started\n", myId);

  while(1){
    OBLT_startEating(t, myId);
    SS_eatingStart(s, myId);
    sthread_yield();
    SS_eatingDone(s, myId);
    OBLT_doneEating(t, myId);
    /* think */
  }
              
}


